package org.example.datasource;

import com.alibaba.druid.pool.DruidDataSource;
import lombok.extern.slf4j.Slf4j;
import org.example.utils.AESUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;
import org.springframework.stereotype.Component;

import java.util.Iterator;

/*@Component
public class SecretDecoder implements EnvironmentPostProcessor {
    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        MutablePropertySources mutablePropertySources = environment.getPropertySources();
        Iterator<PropertySource<?>> iterator = mutablePropertySources.iterator();
        String decryptVal = null;
        while(iterator.hasNext()){
            PropertySource propertySource = iterator.next();
            if(propertySource.getName().equals("spring.datasource.password")) {
                String value = (String)propertySource.getProperty("spring.datasource.password");
                try {
                    decryptVal = AESUtils.aesDecrypt(value);
                    break;
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}*/

@Component
@Slf4j
public class SecretDecoder implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if(bean instanceof DataSourceProperties){
            DataSourceProperties dataSourceProperties = (DataSourceProperties)bean;
            try {
                String password = dataSourceProperties.getPassword();
                log.info("password="+password);
                String decryptPwd = AESUtils.aesDecrypt(password);
                dataSourceProperties.setPassword(decryptPwd);
            } catch (Exception e) {
                log.error("解密失败，", e);
                dataSourceProperties.setPassword(dataSourceProperties.getPassword());
            }
        }
        return bean;
    }
}
